// index.js
// 获取应用实例
import Toast from 'tdesign-miniprogram/toast/index';
import {
    wgs84togcj02
} from "../../utils/gnss.js"
const app = getApp()
import {
    getAllDevice,
    editDeviceName,
    delDevice,
    editModel
} from "../../utils/api.js";
Page({
    data: {
        // 中心点经纬度
        longitude: "",
        latitude: "",
        // 地图标点
        markers: [],
        markerId: 0,
        showMap: false,
        deviceStatus: false,
        infoData: [],
        // 编辑类
        dialogInputVal: "",
        showWithInput: false,
        showTextAndTitleWithInput: false,
        // 确认类
        confirmBtn: {
            content: '确定',
            variant: 'base'
        },
        showConfirm: false,
        popupInfo: {}
    },
    // 标点点击事件
    onMarkerTap(e) {
        var markerId = e.detail.markerId
        var deviceInfo = this.data.infoData[markerId]
        this.setData({
            markerId: markerId,
            popupInfo: []
        })
        if (this.data.deviceStatus) {
            this.setData({
                popupInfo: deviceInfo,
                visible: true
            })
        }
    },
    onShow(options) {
        this.setInfoData()
    },
    // 弹出层关闭
    onVisibleChange(e) {
        // console.log(e)
        this.setData({
            visible: e.detail.visible,
        });
    },
    // 设置信息
    setInfoData() {
        getAllDevice().then(res => {
            if (res.code == 1) {
                if (res.data.length > 0) {
                    this.setData({
                        deviceStatus: true,
                        infoData: res.data,
                        showMap: true
                    })
                } else {
                    this.setData({
                        showMap: true
                    })
                }
                this.init()
            }
        })
    },
    // 初始化地点
    init() {
        wx.showToast({
            title: "数据加载中...",
            icon: 'loading',
        })
        // 请求数据接口
        // 如果返回错误，地图中心定位到当前位置，清除范围，标点
        // if (true) {
        this.setData({
            markers: [],
            polygon: false
        })
        if (this.data.deviceStatus) {
            // 页面传递过来的参数进行赋值
            let devices = this.data.infoData
            let markerarr = []
            for (let i = 0; i < devices.length; i++) {
                var value = this.funWGS(devices[i].locate.split(",")[1], devices[i].locate.split(",")[0]);
                let marker = {
                    "id": i,
                    "longitude": value.longitude,
                    "latitude": value.latitude,
                    "iconPath": "../../assect/dw.png",
                    "width": "50px",
                    "height": "50px",
                    "power": devices[i].power,
                }
                markerarr.push(marker)
            }
            // 如果有设备获取第0个设备的位置作为中心点
            this.setData({
                markers: markerarr,
                longitude: markerarr[0].longitude,
                latitude: markerarr[0].latitude,
            })
        } else {
            // 如果没有设备则获取用户位置作为中心点
            wx.getLocation({
                type: 'gcj02', // 比较精确
                success: (res) => {
                    // console.log(res)
                    this.setData({
                        latitude: res.latitude,
                        longitude: res.longitude,
                    })
                    this.addMark(res)
                },
                fail: (res) => {
                    Toast({
                        context: this,
                        selector: '#t-toast',
                        duration: 3000,
                        message: res.errMsg,
                    });
                }
            })
        }
    },
    addMark(res) {
        var marker = []
        marker.push({
            id: 0, //标记点 id
            width: 50,
            height: 50,
            longitude: res.longitude,
            latitude: res.latitude,
            iconPath: '../../assect/me.png'
        })
        this.setData({
            markers: marker
        })
    },
    // 将gnss定位纠偏
    funWGS(lat, lng) {
        let lngdm = lng.toString();
        let lngarr = lngdm.split(".");
        let lng2 = parseFloat("0." + lngarr[1]) * 60;
        let lng1 = parseFloat(lngarr[0] * 100) + lng2;
        this.Lngdm = lng1;
        let latdm = lat.toString();
        let latarr = latdm.split(".");
        let lat2 = parseFloat("0." + latarr[1]) * 60;
        let lat1 = parseFloat(latarr[0] * 100) + lat2;
        this.Latdm = lat1;

        //convert wgs84 to cj02
        let cj02 = wgs84togcj02(lng, lat);
        let loa = {
            longitude: cj02[0].toFixed(10),
            latitude: cj02[1].toFixed(10)
        }
        return loa
    },
    // 模式开关事件
    switchChange(e) {
        var bool = e.detail.value
        var id = e.currentTarget.dataset.value
        editModel({
            id: id,
            model: bool
        }).then(res => {
            if (res.code == 1) {
                Toast({
                    context: this,
                    selector: '#t-toast',
                    message: '切换成功'
                });
                this.data.infoData[this.data.markerId].mode = bool
            }
        })
    },
    // 编辑弹框
    handleEdit(e) {
        // console.log(e)
        const {
            key
        } = e.currentTarget.dataset;
        this.setData({
            [key]: true,
            dialogKey: key
        });
    },
    // 编辑确认
    editConfirmDialog(e) {
        var name = this.data.dialogInputVal
        var id = e.currentTarget.dataset.id
        if (!name) {
            Toast({
                context: this,
                selector: '#t-toast',
                message: '请输入设备别名',
            });
        } else {
            editDeviceName({
                id: id,
                name: name
            }).then(res => {
                if (res.code == 1) {
                    Toast({
                        context: this,
                        selector: '#t-toast',
                        message: '修改成功',
                    });
                    this.data.infoData[this.data.markerId].device_name = name
                    this.setData({
                        dialogInputVal: "",
                        showWithInput: false,
                        visible: false
                    })
                    this.init()
                } else {
                    Toast({
                        context: this,
                        selector: '#t-toast',
                        message: res.message,
                    });
                }
            })
        }
    },
    inputChange(e) {
        this.setData({
            dialogInputVal: e.detail.value
        })
    },
    // 取消
    closeDialog() {
        const {
            dialogKey
        } = this.data;
        this.setData({
            [dialogKey]: false
        });
    },
    // 删除确认弹框
    handledel(e) {
        const {
            key
        } = e.currentTarget.dataset;
        this.setData({
            [key]: true,
            dialogKey: key
        });
    },
    // 删除确认
    delConfirm(e) {
        console.log(e)
        var device_id = e.currentTarget.dataset.id
        delDevice({
            id: device_id
        }).then(res => {
            if (res.code == 1) {
                Toast({
                    context: this,
                    selector: '#t-toast',
                    message: '删除成功',
                });
                this.setData({
                    showConfirm: false,
                    visible: false
                });
                this.init()
                this.onLoad()
            }
        })
    },
})